package com.lucy.rabc.service.impl;

import cn.hutool.core.lang.Validator;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.PageResultDTO;
import com.lucy.common.exception.BusinessException;
import com.lucy.rabc.dao.SysDeptDAO;
import com.lucy.rabc.entity.SysDept;
import com.lucy.rabc.entity.SysRole;
import com.lucy.rabc.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SysDeptServiceImpl implements SysDeptService {
    @Autowired
    SysDeptDAO dao;

    @Override
    public PageResultDTO<SysDept> getAll(Pageable pageable, Example<SysDept> example) {
        Page<SysDept> page;

        if(Validator.isEmpty(example)){
            page = dao.findAll(pageable);
        }
        else {
            page = dao.findAll(example,pageable);
        }
        /**
         * 获取分页主体内容
         */
        List<SysDept> list = page.getContent();
        PageResultDTO<SysDept> pageResultDTO = new PageResultDTO<>();


        //封装分页请求结果
        pageResultDTO.setContent(list);
        pageResultDTO.setSize(page.getSize());
        pageResultDTO.setTotalPages(page.getTotalPages());
        pageResultDTO.setNumber(page.getNumber());
        pageResultDTO.setTotalElements(page.getTotalElements());
        return pageResultDTO;
    }

    @Override
    public List<SysDept> getExample(Example<SysDept> example) {
        return dao.findAll(example);
    }

    @Override
    public void deleteOne(Long id) {
        dao.deleteById(id);
    }

    @Override
    public Optional<SysDept> getOne(Long id) {
        return dao.findById(id);
    }

    @Override
    public SysDept saveOne(SysDept sysDept) {
        if (Validator.isNotEmpty(sysDept.getId())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"新建部门DTO不可携带ID");
        }
        return dao.save(sysDept);
    }

    @Override
    public SysDept updateOne(SysDept sysDept) {
        if (Validator.isEmpty(sysDept.getId())) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "更新部门DTO必须携带ID");
        }
        return dao.save(sysDept);
    }
}
